<?php
/**
 * Created by 胡祥能 on 2018/4/18.
 *  email：huxiangneng@jiuletech.com
 */

namespace App\Http\Middleware;

use App\User;
use Closure;
use Illuminate\Support\Facades\Route;

class MyAuth
{
    /**自定义用户权限中间件
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
     */
    public function handle($request, Closure $next)
    {
        $user_cache = $request->session()->get(User::SESSION_KEY);
        $user = User::find($user_cache['id']);

        //TODO 想想这里可不可以不要每次都来查数据库，很耗时间，使用session缓存来
        $current_route = Route::currentRouteName();
        if (!$user->ability(array('admin'), array($current_route))) {
            return response()->view('admin.error', ['message'=>'您没有访问权限']);
        }

        return $next($request);
    }
}